package com.ruoyi.base.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.base.domain.BaseCatalog;
import com.ruoyi.base.mapper.BaseCatalogMapper;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.base.mapper.BaseMetaMapper;
import com.ruoyi.base.domain.BaseMeta;
import com.ruoyi.base.service.IBaseMetaService;

/**
 * 元数据Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-02-12
 */
@Service
public class BaseMetaServiceImpl implements IBaseMetaService 
{
    private static final Logger log = LoggerFactory.getLogger(BaseMetaServiceImpl.class);

    @Autowired
    private BaseMetaMapper baseMetaMapper;
    @Autowired
    private BaseCatalogMapper baseCatalogMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询元数据
     * 
     * @param id 元数据主键
     * @return 元数据
     */
    @Override
    public BaseMeta selectBaseMetaById(Long id)
    {
        return baseMetaMapper.selectBaseMetaById(id);
    }

    /**
     * 查询元数据列表
     * 
     * @param baseMeta 元数据
     * @return 元数据
     */
    @Override
    public List<BaseMeta> selectBaseMetaList(BaseMeta baseMeta)
    {
        return baseMetaMapper.selectBaseMetaList(baseMeta);
    }

    /**
     * 新增元数据
     * 
     * @param baseMeta 元数据
     * @return 结果
     */
    @Override
    public int insertBaseMeta(BaseMeta baseMeta)
    {
        BaseMeta old = baseMetaMapper.selectBaseMetaByNum(baseMeta.getNum());
        if(old != null) {
            throw new ServiceException("元数据'"+baseMeta.getNum()+"'已存在");
        }
        baseMeta.setCreateTime(DateUtils.getNowDate());
        return baseMetaMapper.insertBaseMeta(baseMeta);
    }

    /**
     * 修改元数据
     * 
     * @param baseMeta 元数据
     * @return 结果
     */
    @Override
    public int updateBaseMeta(BaseMeta baseMeta)
    {
        BaseMeta old = baseMetaMapper.selectBaseMetaByNum(baseMeta.getNum());
        if(old != null && !old.getId().equals(baseMeta.getId())) {
            throw new ServiceException("元数据'"+baseMeta.getNum()+"'已存在");
        }
        baseMeta.setUpdateTime(DateUtils.getNowDate());
        return baseMetaMapper.updateBaseMeta(baseMeta);
    }

    /**
     * 批量删除元数据
     * 
     * @param ids 需要删除的元数据主键
     * @return 结果
     */
    @Override
    public int deleteBaseMetaByIds(Long[] ids)
    {
        return baseMetaMapper.deleteBaseMetaByIds(ids);
    }

    /**
     * 删除元数据信息
     * 
     * @param id 元数据主键
     * @return 结果
     */
    @Override
    public int deleteBaseMetaById(Long id)
    {
        return baseMetaMapper.deleteBaseMetaById(id);
    }


    /**
   * 导入数据
   *
   * @param dataList 数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName 操作用户
   * @return 结果
   */
    @Override
    public String importData(List<BaseMeta> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Map<String, Long> cataMap = baseCatalogMapper.selectBaseCatalogList(new BaseCatalog()).stream().collect(Collectors.toMap(BaseCatalog::getName, BaseCatalog::getId));
        for (BaseMeta row : dataList)
        {
            try
            {
                row.setCataId(cataMap.get(row.getCataName()));

                BeanValidators.validateWithException(validator, row);

                BaseMeta old = baseMetaMapper.selectBaseMetaByNum(row.getNum());
                if(old == null) {
                    insertBaseMeta(row);
                    row.setCreateBy(operName);
                    successNum++;
                }else if(isUpdateSupport){
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    updateBaseMeta(row);
                    successNum++;
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、元数据 " + row.getNum() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum;// + "、数据 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
